#!/bin/bash
###
 # @Author: admin@attacker.club
 # @Date: 2022-06-20 18:08:05
 # @LastEditTime: 2022-11-10 14:57:01
 # @Description: 
 # curl -sL http://wuyou.run/services/openresty.sh|bash
### 


# 判断是否root用户
if [ $(id -u) -ne 0 ]; then 
  color_msg error "### This script must be run as root !!!"
  exit 1
fi

#### -----------  打印颜色 ----------- #### 
function color_message(){
  case "$1" in
  "error"|"red")
    echo -e "\e[1;31m$2\e[0m"
    ;;
  "warn"|"yellow")
    echo -e "\e[1;33m$2\e[0m"
    ;;
  "info"|"blue")
    echo -e "\e[1;34m$2\e[0m"
    ;;
  "success"|"green")
    echo -e "\e[1;32m$2\e[0m"
    ;;
  esac
}


color_message  "info" "---- install base package ----"
yum --debuglevel=1 install pcre-devel openssl-devel gcc curl -y


color_message  "info" "---- Check the installation package ----"
if   [ ! -f openresty-1*.tar.gz ];then
curl -O -L  https://openresty.org/download/openresty-1.19.9.1.tar.gz
fi
if   [ ! -f openresty.template ];then
  wget -c http://wuyou.run/services/openresty.template
fi
if   [ ! -f openresty.nginx.conf ];then
   wget -c http://wuyou.run/services/openresty.nginx.conf
fi
if   [ ! -f openresty.logrotate ];then
   wget -c http://wuyou.run/services/openresty.logrotate
fi


color_message  "info" "---- Compile the installation ----"
tar zxvf openresty-1.*.tar.gz  1>/dev/null
cd  openresty-*/
./configure --with-http_stub_status_module --with-http_v2_module --with-http_realip_module 
make
make install

cd ..
ln -s /usr/local/openresty/nginx  /usr/local/nginx
ln -s  /usr/local/nginx/sbin/nginx  /bin/
 
color_message  "info" "---- user authorization ----"
mkdir  /usr/local/nginx/conf/vhosts/ -p
mkdir /www
groupadd --system www
useradd --system  -g www -d /www -s /sbin/nologin -c "Web service" www
# useradd  -M -s /sbin/nologin -g www  -d /www www
chmod 770 /www && chown -R www:www /www # 添加www组和www用户

mv openresty.nginx.conf   /usr/local/nginx/conf/nginx.conf 
mv  openresty.template  /usr/local/nginx/conf/vhosts/test.com.conf
cat > /usr/local/nginx/conf/vhosts/default_deny.conf <<EOF
# 默认请求拒绝
server {
listen 80 default_server;
server_name _;
return 444;
access_log  /usr/local/nginx/logs/default.log;
}
EOF


color_message  "info" "---- clear log regularly ----"
mv openresty.logrotate   /etc/logrotate.d/openresty
logrotate /etc/logrotate.conf

color_message  "info" "---- 将lualib库链接到默认路径 ----"
rm -fr /usr/local/lib/resty
ln -s /usr/local/openresty/lualib/resty /usr/local/lib

color_message  "success" "---- nginx -t 配置检查 ----"
nginx -t
color_message  "info" "config: /usr/local/nginx/conf/vhosts"